<template>
  
  <div id="reward-home">

      <div style="background-color:#f0f0f0;">

      <a-menu mode="horizontal">
        <a-sub-menu>
            <span slot="title" class="submenu-title-wrapper" >
              <a-avatar :src="userinfo.avatar" style="margin-left:0.25rem; margin-right:0.55rem;" />
              {{ usertitle }} 
            </span>
            <a-menu-item-group title="应用中心">
            <a-menu-item key="setting:1" :to="`/stock/message`"  @click="redirectView('/stock/message')" >
                审批
            </a-menu-item>
            <a-menu-item key="setting:2" :to="`/stock/workspace`" @click="redirectView('/stock/workspace')" >
                工作台
            </a-menu-item>
            <a-menu-item key="setting:3" :to="`/stock/ranking`" @click="redirectView('/stock/ranking')" >
                排行榜
            </a-menu-item>
            <a-menu-item key="setting:4" :to="`/stock/setting`"  >
                系统设置
            </a-menu-item>
            </a-menu-item-group>
        </a-sub-menu>
      </a-menu>

      <a-row :gutter="24">
        <keep-alive>
          <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">

            <div id="" class="" style="padding-left:2.75rem;padding-top:0.25rem;padding-bottom:0.25rem;background-color:#fefefe;" >
              <a-breadcrumb>
                <template v-for="(elem,index) in breadcrumb">
                  <a-breadcrumb-item :key="elem.icon" :index="index" >
                    <a-icon :type="elem.icon" />
                    <span @click="redirectView(elem.path)">{{ elem.text }}</span>
                  </a-breadcrumb-item>
                </template>
              </a-breadcrumb>
            </div>

            <!-- 录入变更记录 -->
            <div style="background-color:#f0f0f0;">

              <div id="legal-apply-content" class="reward-apply-content" style="height:auto; background-color:#fefefe; margin-top:0px; margin-left: 2.5rem; margin-right: 2.5rem; margin-bottom: 5rem; border: 1px solid #f0f0f0; front-size: 1rem;" >

                <div class="reward-apply-header" style="height:80px; width:100%; text-align:center; margin-top:20px; font-size: 1.5rem; ">
                  录入变更记录
                </div>

                <div class="reward-apply-content-item reward-apply-content-title" style="padding-top:5px;">
                   <a-row style="border-top: 1px dash #f0f0f0;" >
                    <a-col class="reward-apply-content-title-text" :span="4" style="font-size:1.1rem;">
                      著作信息
                    </a-col>
                   </a-row>
                </div>

                <div v-if="isNull(id)" class="reward-apply-content-item" style="margin-top:5px;margin-bottom:5px; margin-right:10px;">
                  <a-row>
                    <a-col :span="4" style="font-size:1.0rem; margin-top:5px; text-align: center;">
                      <span style="position:relative;" ><span style="color:red;margin-right:0px;position:absolute;left:-10px;top:0px;">*</span>填报日期</span>
                    </a-col>
                    <a-col :span="8">
                      <a-input v-model="alteration.create_time" readonly placeholder="请填写填报日期！" @blur="validFieldToast('create_time')" style="border: 0px solid #fefefe;  border-bottom: 1px solid #f0f0f0;"  />
                    </a-col>
                    <a-col :span="4" style="font-size:1.0rem; margin-top:5px; text-align: center;">
                      <span style="position:relative;" ><span style="color:red;margin-right:0px;position:absolute;left:-10px;top:0px;">*</span>填报人员</span>
                    </a-col>
                    <a-col :span="8">
                      <a-input v-model="alteration.create_by" readonly placeholder="请输入填报人员！" @blur="validFieldToast('create_by')" style="border: 0px solid #fefefe;  border-bottom: 1px solid #f0f0f0;"  />
                    </a-col>
                  </a-row>
                </div>

                <div class="reward-apply-content-item" style="margin-top:5px;margin-bottom:5px; margin-right:10px;">
                  <a-row>
                    <a-col :span="4" style="font-size:1.0rem; margin-top:5px; text-align: center;">
                      <span style="position:relative;" ><span style="color:red;margin-right:0px;position:absolute;left:-10px;top:0px;">*</span>公司名称</span>
                    </a-col>
                    <a-col :span="8">
                      <a-auto-complete v-model="alteration.companyName" :data-source="options.companyList" placeholder="请输入公司名称！" @blur="validFieldToast('companyName')" style="width:100%; border: 0px solid #fefefe;  border-bottom: 1px solid #f0f0f0;" :filter-option="filterOption" />
                    </a-col>
                  </a-row>
                </div>

                <div class="reward-apply-content-item" style="margin-top:5px;margin-bottom:5px; margin-right:10px;">
                  <a-row>
                    <a-col :span="4" style="font-size:1.0rem; margin-top:5px; text-align: center;">
                      <span style="position:relative;" ><span style="color:red;margin-right:0px;position:absolute;left:-10px;top:0px;">*</span>变更日期</span>
                    </a-col>
                    <a-col :span="8">
                      <a-date-picker v-model="alteration.time" :default-value="options.create_time" placeholder="请输入变更日期！" @blur="validFieldToast('time')" style="width:100%; border: 0px solid #fefefe;  border-bottom: 1px solid #f0f0f0;" />
                    </a-col>
                    <a-col :span="4" style="font-size:1.0rem; margin-top:5px; text-align: center;">
                      <span style="position:relative;" ><span style="color:red;margin-right:0px;position:absolute;left:-10px;top:0px;">*</span>变更项目</span>
                    </a-col>
                    <a-col :span="8">
                      <a-input  v-model="alteration.name" placeholder="请输入变更项目！" style="border: 0px solid #fefefe;  border-bottom: 1px solid #f0f0f0; width:100%; border-width: 0px 0px 1px; border-style: solid; border-color: rgb(254, 254, 254) rgb(254, 254, 254) rgb(240, 240, 240); border-image: initial;" />
                    </a-col>
                  </a-row>
                </div>

                <div class="reward-apply-content-item" style="margin-top:5px;margin-bottom:5px; margin-right:10px;">
                  <a-row>
                    <a-col :span="4" style="font-size:1.0rem; margin-top:5px; text-align: center;">
                      <span style="position:relative;" ><span style="color:red;margin-right:0px;position:absolute;left:-10px;top:0px;">*</span>变更前内容</span>
                    </a-col>
                    <a-col :span="8">
                      <a-input v-model="alteration.pre_value" :default-value="options.college" placeholder="请输入变更前内容！" @blur="validFieldToast('college')" style="width:100%; border: 0px solid #fefefe;  border-bottom: 1px solid #f0f0f0;" />
                    </a-col>
                    <a-col :span="4" style="font-size:1.0rem; margin-top:5px; text-align: center;">
                      <span style="position:relative;" ><span style="color:red;margin-right:0px;position:absolute;left:-10px;top:0px;">*</span>变更后内容</span>
                    </a-col>
                    <a-col :span="8">
                      <a-input v-model="alteration.value" placeholder="请输入变更后内容！" @blur="validFieldToast('start_time')" style="width:100%; border: 0px solid #fefefe;  border-bottom: 1px solid #f0f0f0;" />
                    </a-col>
                  </a-row>
                </div>

                <div class="reward-apply-content-item" style="margin-top:5px;margin-bottom:5px; margin-right:10px;">
                  <a-row>
                    <a-col :span="4" style="height:auto; font-size:1.0rem; margin-top:5px; text-align: center;">
                      <span style="position:relative;" ><span style="color:red;margin-right:0px;position:absolute;left:-10px;top:0px;"></span>备注信息</span>
                    </a-col>
                    <a-col :span="20">
                      <a-textarea
                        v-model="alteration.remark"
                        placeholder="请输入备注信息！"
                        :auto-size="{ minRows: 4, maxRows: 100 }"
                        style="height:60px; border: 0px solid #fefefe;  border-bottom: 1px solid #f0f0f0;"
                      />
                    </a-col>
                  </a-row>
                </div>

                <div class="reward-apply-content-item" style="margin-top:5px;margin-bottom:5px; margin-right:10px;">
                  <a-row>
                    <a-col :span="4" style="font-size:1.0rem; margin-top:5px; text-align: center;">
                      <span style="position:relative;" ><span style="color:red;margin-right:0px;position:absolute;left:-10px;top:0px;"></span>上传附件</span>
                    </a-col>
                    <a-col :span="8">
                      <a-upload name="file" :multiple="false" :action="uploadURL" @change="uploadComplete" style="width:85%;" >
                        <a-button> <a-icon type="upload" /> 上传 </a-button>
                      </a-upload>
                    </a-col>
                  </a-row>
                </div>

                <div v-show="role != 'view' && isNull(id) " class="reward-apply-content-item" style="margin-top:35px;margin-bottom:5px; margin-right:10px;">
                   <a-row style="border-top: 1px dash #f0f0f0;" >
                    <a-col :span="8">
                    </a-col>
                    <a-col class="reward-apply-content-title-text" :span="4" style="">
                      <a-button type="primary" style="width: 120px;color:c0c0c0;" @click="handleSave();"  >
                        保存
                      </a-button>
                    </a-col>
                    <a-col class="reward-apply-content-title-text" :span="4" style="">
                      <a-button type="primary" style="width: 120px;" @click="handleApply();"  >
                        提交
                      </a-button>
                    </a-col>
                    <a-col :span="8">
                    </a-col>
                   </a-row>
                </div>

                <div v-show="role != 'view' && !isNull(id)  " class="reward-apply-content-item" style="margin-top:35px;margin-bottom:5px; margin-right:10px;">
                   <a-row style="border-top: 1px dash #f0f0f0;" >
                    <a-col :span="8">
                    </a-col>
                    <a-col class="reward-apply-content-title-text" :span="4" style="margin-left:100px;">
                      <a-button type="primary" style="width: 120px;color:c0c0c0;" @click="handlePatch();"  >
                        修改
                      </a-button>
                    </a-col>
                    <a-col :span="8">
                    </a-col>
                   </a-row>
                </div>

                <div style="height:100px;">
                </div>
              </div>
            </div>
          </a-col>
        </keep-alive>
      </a-row>
    </div>
  </div>
</template>
<script>
import * as workconfig from '@/request/workconfig';

export default {
  mixins: [window.mixin],
  data() {
    return {
      iswechat:false,
      iswework:false,
      pageName: "工商管理",
      momentNewMsg: true,
      activeTabKey: 3,
      acceptType:'*/*',
      uploadURL:'https://api.yunwisdom.club:30443/gateway-xmysql/@172.18.1.45@/upload',
      tablename:'bs_company_flow_alteration',
      size: 0,
      options:{
        create_time:moment(dayjs().format('YYYY-MM-DD'),'YYYY-MM-DD'),
        in_time:moment(dayjs().format('YYYY-MM-DD'),'YYYY-MM-DD'),
        establish_time:moment(dayjs().format('YYYY-MM-DD'),'YYYY-MM-DD'),
        start_time:moment(dayjs().format('YYYY-MM-DD'),'YYYY-MM-DD'),
        coop_time:moment(dayjs().format('YYYY-MM-DD'),'YYYY-MM-DD'),
        out_time:moment(dayjs().format('YYYY-MM-DD'),'YYYY-MM-DD'),
        companyList:[],
      },
      id:'',
      alteration: {
          create_time: dayjs().format('YYYY-MM-DD'),
          create_by:'',
          time: dayjs().format('YYYY-MM-DD'), // date null comment '变更日期',
          name:'', // varchar(256) null comment '项目名称',
          pre_value:'', // text null comment '变更前内容',
          value:'', // text null comment '变更后内容',
          companyID: 0, // int null,
          companyName:'', // varchar(256) null,
          remark:'',
          files:'',
          xid:'',
      },
      data: [],
      readonly: false,
      userList:[],
      firmlist:[],
      firmNamelist:[],
      release_userlist:[],
      approve_userlist:[],
      approve_executelist:[],
      role:'',
      file:'',
      selectedSheet: null,
      sheetName: null,
      collection: [{ }],
      userinfo: '',
      usertitle:'',
      columns: workconfig.columns.reward.items,
      wfcolumns: workconfig.columns.reward.wfcolumns,
      message: workconfig.compValidation.legalapply.message,
      valid: workconfig.compValidation.legalapply.valid,
      goodsborrowtype: workconfig.goodsborrowtype,
      diplomaType: workconfig.compcolumns.diplomaTypeColumns,
      acceptType: workconfig.compcolumns.acceptType,
      commonTypeColumns: workconfig.compcolumns.commonTypeColumns,
      sealTypeColumns: workconfig.compcolumns.sealTypeColumns,
      territoryList:[ '家庭纠纷', '借款借贷', '交通事故', '房产纠纷', '刑事辩护', '合同纠纷', '经济纠纷', '土地纠纷', '劳动工伤', '消费权益', '医疗纠纷', '行政诉讼', '公司事务', '知识产权', '保险理赔', '征地拆迁', '涉外海关', '工程建设', '综合咨询', ],
      breadcrumb:[{icon:'home',text:'首页',path:'/stock/workspace'},{icon:'user',text:'记录管理',path:'/stock/workspace'},{icon:'form',text:'录入变更记录',path:''}],
      statusType:{'valid':'有效','invalid':'删除'},
      zoneType:{'领地集团总部':'领地集团总部','成渝区域':'成渝区域','两湖区域':'两湖区域','川北区域':'川北区域','川南区域':'川南区域','中原区域':'中原区域','攀西区域':'攀西区域','新疆区域':'新疆区域','大湾区域':'大湾区域','北京区域':'北京区域'},
    };
  },
  activated() {
    this.queryInfo();
  },
  mounted() {
    this.queryInfo();
  },
  methods: {
      moment,
      isNull:Betools.tools.isNull,
      deNull:Betools.tools.deNull,

      // 名称过滤
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
        );
      },

      // 执行上传操作
      uploadComplete(info) {
          if (info.file.status === 'done') {
            this.alteration.files = info.file.response.name + `###${info.file.name}`;
            this.$message.success(`${info.file.name} file uploaded successfully`);
          } else if (info.file.status === 'error') {
            this.$message.error(`${info.file.name} file upload failed.`);
          }
      },

      // 企业微信登录处理函数
      async  weworkLogin  (codeType = 'search', systemType = 'search', version = 'v4')  {
          /**
           URL直连模式登陆：http://stock.yunwisdom.club:30080/#/?mode=session&mobile=19999763013&account=bWVuZ3Fm
            1. mobile请替换为登录人的mobile。
            2. account请替换为登录人的account，注意account需要使用window.btoa('args')函数处理一下。
           */
          return await Betools.query.weworkLogin(codeType, systemType, version);
      },
      
      // 执行页面跳转
      async redirectView(path) {
          Betools.tools.isNull(path) ? null: this.$router.push(path);
      },
     
      // 获取基础信息
      async queryInfo() {
        try {

          try {
            this.iswechat = Betools.tools.isWechat(); //查询当前是否微信端
            this.iswework = Betools.tools.isWework(); //查询是否为企业微信
          } catch (error) {
            console.error(error);
          }
          
          try {
            const weworkinfo = await this.weworkLogin('search','search','v4'); //查询当前登录用户
            this.userinfo = weworkinfo.userinfo;
            this.usertitle = weworkinfo.usertitle;
            this.back = Betools.tools.getUrlParam('back') || '/stock/workspace'; //查询上一页
          } catch (error) {
            console.error(error);
          }
          
          const userinfo = await Betools.storage.getStore('system_userinfo');  //获取用户基础信息
          try {
            this.alteration.create_by = (userinfo ? userinfo.realname || userinfo.name || userinfo.lastname : '');
            this.alteration.apply_username = (userinfo ? userinfo.username : '');
          } catch (error) {
            console.error(error);
          }

          const companyList = await Betools.manage.queryTableData('bs_company_flow_data' , `_where=(status,eq,valid)&_fields=company&_p=0&_size=10000`);
          try {
            this.options.companyList = companyList.map(e=>e.company);
          } catch (error) {
            console.error(error);
          }
         
          const id = this.id = Betools.tools.getUrlParam('id');
          if(!Betools.tools.isNull(id)){
            this.company = await this.handleList(this.tablename , id);
          }

        } catch (error) {
          console.log(error);
        }
      },

      // 查询不同状态的律所数据
      async handleList(tableName , id){
        let element = await Betools.query.queryTableData(tableName , id);
        return Betools.tools.isNull(element) ? element : {};
      },

      // 验证字段
      validField(fieldName){
        return Betools.tools.isNull(this.alteration[fieldName]);
      },

      // 验证字段信息
      validFieldToast(fieldName){
        const tipsession = { companyName: '请输入公司名称！', time:'请输入变更日期！', name:'请输入变更项目名称！', pre_value:'请输入变更前内容！',value:'请输入变更后内容！', };
        const flag = this.validField(fieldName);
        if(flag){
          Betools.tools.isNull(tipsession[fieldName]) ? null : this.$toast.fail(`${tipsession[fieldName]}！` );
          return false;
        }
      },
      
      // 用户提交入职登记表函数
      async handleApply() {
        await this.handleSave(); //先执行保存操作，保存完毕后执行流程跳转功能
      },

      // 保存用户数据但是不提交
      async handleSave(){
        
        this.loading = true; // 显示加载状态
        const userinfo = await Betools.storage.getStore('system_userinfo'); // 获取用户基础信息
        const id = Betools.tools.queryUniqueID(); // 表单ID

        try {
          this.alteration.create_time = dayjs().format('YYYY-MM-DD');
          this.alteration.create_by = (userinfo ? userinfo.realname || userinfo.name || userinfo.lastname : '');
        } catch (error) {
          console.error(error);
        }

        const tipsession = { companyName: '请输入公司名称！', time:'请输入变更日期！', name:'请输入变更项目名称！', pre_value:'请输入变更前内容！',value:'请输入变更后内容！', };
        const keys = Object.keys(tipsession); // 验证数据是否已经填写

        const invalidKey =  keys.find(key => {
          const flag = this.validField(key); // const returnValue = flag ? key : '';
          return flag;
        });

        if(!Betools.tools.isNull(invalidKey)){
            return await vant.Dialog.alert({  title: '温馨提示',  message: `您好，${tipsession[invalidKey]}`, });
        }

        // 是否确认提交此自由流程?
        this.$confirm({
            title: "确认操作",
            content: "是否确认提交此变更记录申请单?",
            onOk: async() => {
                  const alteration  = JSON.parse(JSON.stringify(this.alteration));
                  alteration.id = id;
                  const result = await Betools.manage.postTableData(this.tablename , alteration); // 向表单提交form对象数据
                  if(result && result.error && result.error.errno){ //提交数据如果出现错误，请提示错误信息
                      return await vant.Dialog.alert({  title: '温馨提示',  message: `系统错误，请联系管理人员，错误编码：[${result.error.code}]. `, });
                  }
                  this.loading = false; //设置状态
                  this.readonly = true;
                  this.role = 'view';
                  this.handleList(this.tablename , id);
                  return vant.Dialog.alert({  title: '温馨提示',  message: `变更记录提交成功！`, }); //this.$toast.success('律师录入申请成功！');
               }
          });
      },

      // 修改用户数据但是不提交
      async handlePatch(){
        
        this.loading = true; // 显示加载状态
        const userinfo = await Betools.storage.getStore('system_userinfo'); // 获取用户基础信息
        const id = Betools.tools.getUrlParam('id'); // 表单ID

        const tipsession = { companyName: '请输入公司名称！', time:'请输入变更日期！', name:'请输入变更项目名称！', pre_value:'请输入变更前内容！',value:'请输入变更后内容！', };
        const keys = Object.keys(tipsession); // 验证数据是否已经填写

        const invalidKey =  keys.find(key => {
          const flag = this.validField(key); // const returnValue = flag ? key : '';
          return flag;
        });

        if(!Betools.tools.isNull(invalidKey)){
            return await vant.Dialog.alert({  title: '温馨提示',  message: `您好，${tipsession[invalidKey]}`, });
        }

        //是否确认提交此自由流程?
        this.$confirm({
            title: "确认操作",
            content: "是否确认修改此设立公司申请单?",
            onOk: async() => {
                  const alteration  = JSON.parse(JSON.stringify(this.alteration));
                  const result = await Betools.manage.patchTableData(this.tablename, id, alteration); // 向表单提交form对象数据
                  if(result && result.error && result.error.errno){ //提交数据如果出现错误，请提示错误信息
                      return await vant.Dialog.alert({  title: '温馨提示',  message: `系统错误，请联系管理人员，错误编码：[${result.error.code}]. `, });
                  }
                  this.loading = false;
                  this.readonly = true;
                  this.role = 'view';
                  this.handleList(this.tablename , id);
                  return vant.Dialog.alert({  title: '温馨提示',  message: `修改操作成功！`, }); //this.$toast.success('律师修改操作成功！');
               }
          });
      },

  },
};
</script>
<style scoped >
    @import "../../../assets/css/reward.home.css";
    @import "../../../assets/css/reward.apply.css";
</style>
